<!doctype html>
<html>

  <head>
    <meta charset="utf-8">
    <title>设备档案编辑</title>
    <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
    <link href="../../../css/mui.min.css" rel="stylesheet" />
    <link href="../css/common.css" rel="stylesheet" />
    <link href="../css/iconfont.css" rel="stylesheet" />
    <link href="../../../css/mui.picker.css" rel="stylesheet" />
    <link href="../../../css/mui.poppicker.css" rel="stylesheet" />
    <style>
      .mui-btn, button, input[type=button], input[type=reset], input[type=submit] {
        padding: 6px 10px;
      }
      .mui-popover {
        height: 180px;
        width: 200px;
      }
      .item input{
        height: auto;
        padding: 6px 10px;
        font-size: 14px;
        margin-bottom: 0px;
      }
    </style>
  </head>

  <body>
    <div class="container" id="container">
      <header class="mui-bar mui-bar-nav">
        <a class="mui-action-back mui-icon mui-icon-left-nav mui-pull-left"></a>
        <h1 class="mui-title">设备档案编辑</h1>
      </header>

      <div class="mui-content bg-white" style="padding-bottom: 60px;">
        <div class="content-Title">
          <span class="titleB">功能位置编码</span>
        </div>
        <div class="content">
          <div class="item flex">
            <div class="text-grey">功能位置编码:</div>
            <div class="text-black">{{ detail.mdmCode }}</div>
          </div>
          <div class="item flex" v-if="detail.parentName">
            <div class="text-grey">上级设备:</div>
            <div class="text-black">{{ detail.parentName }}</div>
          </div>
        </div>
        <div class="content-Title">
          <span class="titleB">区域信息</span>
        </div>
        <div class="content">
          <div class="item flex">
            <div class="text-grey">所属区域:</div>
            <div class="text-black">{{ detail.areaNames }}</div>
          </div>
          <div class="item flex">
            <div class="text-grey">所属场站:</div>
            <div class="text-black">{{ detail.stationNames }}</div>
          </div>
          <div class="item flex align-center">
            <div class="text-grey">所属项目:</div>
            <div class="text-black flex-sub mui-text-right"><input type="text" placeholder="请输入" v-model="detail.projectNames" readonly="readonly"
                @click="project()"></div>
          </div>
          <div class="item flex align-center">
            <div class="text-grey">项目公司:</div>
            <div class="text-black flex-sub mui-text-right"><input type="text" placeholder="请输入" v-model="detail.projectCompanyName" readonly="readonly"
                @click="company()"></div>
          </div>
        </div>
        <div class="content-Title">
          <span class="titleB">设备信息</span>
        </div>
        <div class="content">
          <div class="item flex align-center">
            <div class="text-grey">设备名称:</div>
            <div class="text-black flex-sub mui-text-right"><input type="text" placeholder="普通输入框" v-model="detail.deviceName"></div>
          </div>
          <div class="item flex">
            <div class="text-grey">设备型号:</div>
            <div class="text-black">{{ detail.sn }}</div>
          </div>
        </div>
        <div class="content-Title">
          <span class="titleB">属性信息</span>
        </div>
        <div class="content" v-cloak>
          <!-- {{ detail.model.propDatas}} -->
          <div class="item flex align-center" key="domain.id" v-for="domain in detail.model.propDatas">
            <div class="text-grey" style="width: 65px;">{{domain.mdName}}:</div>
            <div class="text-black flex-sub mui-text-right" v-if="domain.mdPropType != 10" style="max-width: 75%;">
              <input type="text" v-model="domain.value" v-if="domain.mdPropType == '0' && domain.mdJavaType != 'Enum'" />
              <div @click="picker(domain)" v-if="domain.mdPropType == 0 && domain.mdJavaType == 'Enum'" style="position: relative;">
                 <input type="text" readonly="readonly"/>
                  <span v-for="(item, index) in domain.dictDatas" :key="item.value + index" v-if="domain.value==item.value" style="position: absolute;left: 4px;padding: 6px 10px;top: 0;">{{item.label}}</span>
              </div>
            </div>
           <div v-if="domain.mdUnit">
              <span class="form-subtext" v-if="domain.mdUnit">{{domain.mdUnit}}</span>
            </div>
            <div v-if="domain.mdPropType == 10" style="float: left;margin-right: 10px; text-align: right;">
              <span v-if="domain.attachmentPath">{{domain.attachmentName}}</span>
              <span v-else class="text-grey">未上传</span>
              <a href="javascript:void(0);" v-if="domain.attachmentPath" @click="open(domain.attachmentName,domain.fileUrl,domain.attachmentName)">预览</a></div>

          </div>
          <!-- <input type="file" id="file" multiple="multiple" onchange="handleFile()"> -->
          <!-- <div class="item flex">
            <div class="text-grey">制度标准规范:</div>
            <div class="text-black flex-sub">制度标准规范.doc 5M</div>
            <div class=""><a href="" class="padding-right-xs">下载</a><a href="">预览</a></div>
          </div> -->
        </div>
      </div>
      <div class="footer fixed" style="padding:10px 10px">
        <div class="flex justify-center padding-lr">
          <button type="button" class="mui-btn mui-btn-primary margin-right-lg flex-sub mui-btn-outlined" @click="back()">取消</button>
          <button type="button" class="mui-btn mui-btn-primary flex-sub" @click="tosubmit()">提交</button>
          <!-- <button type="button" class="mui-btn mui-btn-primary">编辑</button> -->
        </div>
      </div>
      <div class="popUp" id="popUp" style="display: none;">
        <form action="" class="popUpContent">
          <div class="item flex">
            <div class="label">审批：</div>
            <div class="flex">
              <div class="mui-input-row mui-radio mui-left">
                <label>通过</label>
                <input name="radio1" type="radio">
              </div>
              <div class="mui-input-row mui-radio mui-left">
                <label>未通过</label>
                <input name="radio1" type="radio" checked>
              </div>
            </div>
          </div>
          <div class="item flex">
            <div class="label">意见：</div>
            <div class="flex-sub ">
              <textarea id="textarea" rows="5" placeholder="多行文本框"></textarea>
            </div>
          </div>
          <div class="item flex">
            <div class="label"></div>
            <div class="flex-sub flex">
              <button type="button" class="mui-btn mui-btn-primary mui-btn-outlined flex-sub">取消</button>
              <button type="button" class="mui-btn mui-btn-primary flex-sub" @click="tosubmit()">确认111</button>
            </div>
          </div>
        </form>
      </div>
    </div>

  </body>
  <script src="../../../js/mui.min.js"></script>
  <script src="../../../js/vue.js"></script>
  <script src="../../../js/jquery-1.7.2.min.js"></script>
  <script src="../../../js/common.js"></script>
  <script src="../js/mkeyplus.base.js"></script>
  <script src="../../../js/mui.picker.js" type="text/javascript" charset="utf-8"></script>
  <script src="../../../js/mui.poppicker.js" type="text/javascript" charset="utf-8"></script>
  <script src="../../../js/mui.dtpicker.js"></script>
  <script type="text/javascript">
    mui.init()
    var mask = null;
    var detailVm = null;
    var cv = null; // 当前webview
    var pageId = ""; //获取详情id
    mui.plusReady(function() {
      cv = plus.webview.currentWebview();
      pageId = cv.pageId || '';
      console.log(pageId)
      detailVm.getDetail(pageId)
    })
    detailVm = new Vue({
      el: "#container",
      data: {
        detail: {
          model: {
            propDatas: [],
          },
        },
        dictDatas: []
      },
      created: function() {},
      methods: {
        view: function() {
          mui.openWindow({
            url: '../file/fileChildren.html',
            id: '../file/fileChildren.html',
            createNew: true, //是否重复创建同样id的webview，默认为false:不重复创建，直接显示
            extras: {
              pageId: pageId
            }
          })
        },
        picker(domain) {
          console.log(JSON.stringify(domain))
          var newArr = [];
          var item = domain.dictDatas
          var picker = new mui.PopPicker();
          for (var i = 0; i < item.length; i++) {
            //这里是转换成picker能用的数据格式
            newArr.push({
              value: item[i].value,
              text: item[i].label
            });
          }
          picker.setData(newArr);
          picker.show(function(items) {
            domain.value = items[0].value;
            domain.label = items[0].label;
            console.log(JSON.stringify(domain))
          })
        },
        getDetail: function(pageId) {
          plus.nativeUI.showWaiting('加载中...');
          var that = this;
          mui.baseApp.httpRequst("/api/metadataDocument/info", {
            copyFlag: false,
            childModelFlag: true,
            id: pageId
          }, function(data) {
            let {
              childDocuments,
              model
            } = data;
            let {
              childModels,
              propDatas
            } = model;
            if (childDocuments && childModels) {
              var childModelsNew = childModels.map((childModel, i) => {
                var filterDoc = childDocuments.filter(
                  element => element.metadataModelId == childModel.id
                );
                return { ...childModel,
                  childDocuments: filterDoc
                };
              });
              data.model.childModels = childModelsNew;
            }
            if (propDatas) {
              var enumNames = [];
              propDatas.forEach(propData => {
                if (propData.mdJavaType == "Enum" && propData.mdDictName) {
                  enumNames.push(propData.mdDictName);
                }
                if (propData.mdPropType == 10 && propData.attachmentPath) {
                  var isUrl = false;
                  var FileSystemURL = "_downloads/"+ propData.id + "/" + propData.attachmentName;
                  plus.io.resolveLocalFileSystemURL(FileSystemURL, function() {
                    console.log('文件已存在')
                    isUrl = true;
                  }, function() {
                    console.log("未找到文件")
                    var dtask = plus.downloader.createDownload(propData.attachmentPath, {filename:"_downloads/" + propData.id + "/" + propData.attachmentName}, function(
                      d, status) {
                      if (status == 200) {
                        var fileUrl = d.filename;
                        console.log(fileUrl);
                        propData.fileUrl = fileUrl;
                      } else {
                        alert("Download failed: " + status);
                      }
                    });
                    dtask.start();
                  });
                  
                   
                  
                }
              });
              if (enumNames.length) {
                mui.baseApp.httpRequst("/api/dictItem/map", {
                  dictName: enumNames.join(","),
                  page: 0,
                  size: 9999
                }, function(resMap) {
                  that.dictDatas = resMap;
                  console.log(JSON.stringify(data.dictDatas))
                  data.model.propDatas = propDatas.map((propData, i) => {
                    // console.log('propData', self.dictDatas, propData.mdDictName)
                    return {
                      ...propData,
                      dictDatas:
                        propData.mdJavaType == "Enum" && propData.mdDictName
                          ? that.dictDatas[propData.mdDictName]
                          : []
                    };
                  });
                  that.detail = data;
                }, function() {
                  console.log("获取数据失败");
                })
              } else {
                data.model.propDatas = propDatas.map((propData, i) => {
                  // console.log('propData', self.dictDatas, propData.mdDictName)
                  return {
                    ...propData,
                    dictDatas: propData.mdJavaType == "Enum" && propData.mdDictName ?
                      self.dictDatas[propData.mdDictName] :
                      []
                  };
                });
              }
            }
            
            that.detail = data
            plus.nativeUI.closeWaiting();
            // console.log(JSON.stringify(that.detail))
          }, function() {
            plus.nativeUI.closeWaiting();
            console.log("获取数据失败");
          })
        },
        project() { //所属项目
          mui.openWindow({
            url: '../file/project.html',
            id: '../file/project.html',
          })
        },
        company() { //所属公司
          mui.openWindow({
            url: '../file/company.html',
            id: '../file/company.html',
          })
        },
        tosubmit() { //编辑提交
          var that = this;
          var form = that.detail;
          let {
            propDatas
          } = this.detail.model;
          var rules = that.initDynamicValidateDefaultValInteger(); //校验属性信息
          if (rules.length > 0) {
            var text = propDatas[rules[0].index].mdName + rules[0].text
            console.log(text)
            mui.toast(text)
            return false;
          }
          console.log(that.detail.version);
          plus.nativeUI.showWaiting('提交中...');
          mui.baseApp.httpRequst("/api/metadataDocument", form, function(data) {

            var page = plus.webview.currentWebview().opener();
            // var id=opener.id
            // var page = plus.webview.getWebviewById(id);
            mui.fire(page, 'update');
            plus.nativeUI.closeWaiting();
            plus.webview.currentWebview().close();
          }, function(res) {
            plus.nativeUI.closeWaiting();
            console.log("提交失败" + res);
          }, 'put')
        },
        upload(event, item) {
          console.log('上传文件的值' + event.target.value)
          var file = event.target.files[0];
          let {
            mdFileType,
            mdFileLimit
          } = item;
          console.log("mdFileLimit", mdFileLimit, item);
          if (mdFileLimit && isNaN(mdFileLimit)) {
            const isLt2M = file.size / 1024 / 1024 < mdFileLimit;
            if (!isLt2M) {
              mui.toast("上传文件大小不能超过" + mdFileLimit + "MB!");
              return false;
            }
          }
          if (mdFileType) {
            let validFileType =
              file.name
              .substring(file.name.lastIndexOf(".") + 1)
              .indexOf(mdFileType) != -1;
            if (!validFileType) {
              mui.toast(`请上传${mdFileType}格式文件!`);
              return false;
            }
          }

        },
        initDynamicValidateDefaultValInteger() { //校验
          let {
            propDatas
          } = this.detail.model;
          var rules = []
          propDatas.forEach((currentRow, index) => {
            var value = currentRow.value
            console.log(currentRow.mdJavaType)
            if (currentRow.mdJavaType == 'Long') {

            } else if (currentRow.mdJavaType == 'Integer') {
              var rule = {

              }
              if (value) {
                if (Number.isNaN(value)) {
                  rule = {
                    index: index,
                    text: "请输入数字"
                  }
                  rules.push(rule)
                } else if (!Number.isInteger(Number(value))) {
                  rule = {
                    index: index,
                    text: "请输入整数数字"
                  }
                  rules.push(rule)
                } else {

                }
              }
            } else if (currentRow.mdJavaType == 'Double') {
              if (value) {
                let reg = /^[+-]?(0|([1-9]\d*))(\.\d+)?$/g;
                if (!reg.test(value)) {
                  var rule = {
                    index: index,
                    text: "请输入正确的浮点类型的数字"
                  }
                  rules.push(rule)
                } else {}
              } else {}
            } else if (currentRow.mdJavaType == 'BigDecimal') {

            } else if (currentRow.mdJavaType == 'Float') {}
          });
          console.log(JSON.stringify(rules))
          return rules;
        },
        back() {
          mui.back()
        },
        open: function(filename, url, filetype) {
          // var dtask = plus.downloader.createDownload(url, {}, function(d, status) {
          //   if (status == 200) {
              var fileUrl = "_downloads/"+ item.id + "/" + item.attachmentName;
              plus.runtime.openFile(fileUrl, {}, function(e) {
                alert('打开失败');
              });
          //   } else {
          //     alert("Download failed: " + status);
          //   }
          // });
          // dtask.start();
        }
      },

    })


    mask = mui.createMask(function() {
      $('#popUp').hide();
    });
    window.addEventListener("chooseItem", function(e) {
      var item = e.detail.item
      detailVm.detail.projectNames = item.name;
    });
    window.addEventListener("chooseCompany", function(e) {
      var item = e.detail.item
      detailVm.detail.projectCompanyName = item.name;
    });
    // mask.show()

    function handleFile() {
      // let $icon = $(".upload-icon");

      let formData = new FormData(),
        fs = $("#file")[0].files;
      formData.append('file', $('#file')[0].files[0]);
      console.log('111111')
      // $.ajax({
      //     type: 'POST',
      //     url: "",
      //     data: formData,
      //     cache: false,
      //     processData: false,
      //     contentType: false,
      //     headers:{"Authorization":"Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJhZG1pbiIsImV4cCI6MTU5OTYzMzkwOSwiaWF0IjoxNTk3MDQxOTA5fQ.a1ayiBUvpUttp7AIxyu2nVqyGMLGQftV5wWF-DuiVUAKPhwyu39LXDVH0Om8s4xz7a-kvJN7r8RZvlqOzsiBCA"},	
      //     success: function (ret) {
      //         alert(ret);
      //     },
      //      error:function(err){
      //         console.log(JSON.stringify(err))
      //     }
      // });
    }
  </script>
</html>
